/**
 * 剑指 Offer 66. 构建乘积数组
 * https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/
 */
const { displayBaseArray } = require('../../libs/public');

/**
 * @param {number[]} a
 * @return {number[]}
 */
function constructArr(a) {
  const leftProducts = new Array(a.length);
  leftProducts[0] = 1;
  let product = 1;
  for (let i = 1; i < a.length; i += 1) {
    product *= a[i - 1];
    leftProducts[i] = product;
  }
  const rightProducts = new Array(a.length);
  rightProducts[a.length - 1] = 1;
  product = 1;
  for (let i = a.length - 2; i >= 0; i -= 1) {
    product *= a[i + 1];
    rightProducts[i] = product;
  }
  const result = new Array(a.length);
  for (let i = 0; i < a.length; i += 1) {
    result[i] = leftProducts[i] * rightProducts[i];
  }
  return result;
}

console.log(displayBaseArray(constructArr([1, 2, 3, 4, 5])) === '[120,60,40,30,24]');
